package com.central.scheduler.worker.processor;

/**
 * @author Tindy
 * @date 2021/10/29
 * @describe
 */

import com.central.scheduler.remote.NettyRemotingClient;
import com.central.scheduler.remote.command.Command;
import com.central.scheduler.remote.command.CommandType;
import com.central.scheduler.remote.config.NettyClientConfig;
import com.central.scheduler.remote.processor.NettyRemoteChannel;
import com.central.scheduler.service.registry.RegistryClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

/**
 * task callback service
 */
@Service
public class TaskCallbackService {
    private final Logger logger = LoggerFactory.getLogger(TaskCallbackService.class);
    private static final int[] RETRY_BACKOFF = {1, 2, 3, 5, 10, 20, 40, 100, 100, 100, 100, 200, 200, 200};

    /**
     * remote channels
     */
    private static final ConcurrentHashMap<Long, NettyRemoteChannel> REMOTE_CHANNELS = new ConcurrentHashMap<>();

    /**
     * zookeeper registry center
     */
    private RegistryClient registryClient;

    /**
     * netty remoting client
     */
    private final NettyRemotingClient nettyRemotingClient;

    public TaskCallbackService() {
        this.registryClient = RegistryClient.getInstance();
        final NettyClientConfig clientConfig = new NettyClientConfig();
        this.nettyRemotingClient = new NettyRemotingClient(clientConfig);
        this.nettyRemotingClient.registerProcessor(CommandType.DB_TASK_ACK, new DBTaskAckProcessor());
        this.nettyRemotingClient.registerProcessor(CommandType.DB_TASK_RESPONSE, new DBTaskResponseProcessor());
    }
    /**
     * add callback channel
     *
     * @param taskInstanceId taskInstanceId
     * @param channel        channel
     */
    public void addRemoteChannel(Long taskInstanceId, NettyRemoteChannel channel) {
        REMOTE_CHANNELS.put(taskInstanceId, channel);
    }
    /**
     * send ack
     *
     * @param taskInstanceId taskInstanceId
     * @param command        command
     */
    public void sendAck(Long taskInstanceId, Command command) {
        NettyRemoteChannel nettyRemoteChannel = getRemoteChannel(taskInstanceId);
        if (nettyRemoteChannel != null) {
            nettyRemoteChannel.writeAndFlush(command);
        }
    }
    /**
     * get callback channel
     *
     * @param taskInstanceId taskInstanceId
     * @return callback channel
     */
    private NettyRemoteChannel getRemoteChannel(Long taskInstanceId) {
        Channel newChannel;
        NettyRemoteChannel nettyRemoteChannel = REMOTE_CHANNELS.get(taskInstanceId);
        if (nettyRemoteChannel != null) {
            if (nettyRemoteChannel.isActive()) {
                return nettyRemoteChannel;
            }
            newChannel = nettyRemotingClient.getChannel(nettyRemoteChannel.getHost());
            if (newChannel != null) {
                return getRemoteChannel(newChannel, nettyRemoteChannel.getOpaque(), taskInstanceId);
            }
        }
        return null;
    }
    private NettyRemoteChannel getRemoteChannel(Channel newChannel, long opaque, Long taskInstanceId) {
        NettyRemoteChannel remoteChannel = new NettyRemoteChannel(newChannel, opaque);
        addRemoteChannel(taskInstanceId, remoteChannel);
        return remoteChannel;
    }

    /**
     * send result
     *
     * @param taskInstanceId taskInstanceId
     * @param command        command
     */
    public void sendResult(Long taskInstanceId, Command command) {
        NettyRemoteChannel nettyRemoteChannel = getRemoteChannel(taskInstanceId);
        if (nettyRemoteChannel != null) {
            nettyRemoteChannel.writeAndFlush(command).addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        remove(taskInstanceId);
                        return;
                    }
                }
            });
        }
    }
    /**
     * remove callback channels
     *
     * @param taskInstanceId taskInstanceId
     */
    public void remove(Long taskInstanceId) {
        REMOTE_CHANNELS.remove(taskInstanceId);
    }
}